import { useState, useRef, useEffect, memo } from "react";
import FormComponent from "../form";
import { Modal } from "antd";
import { ModalProps } from "../../type/modal";

const Index = (props: ModalProps) => {
  const {
    openModalFlag,
    modalTitle,
    FormFiledList,
    close,
    onOk,
    editData,
    detailid,
  } = props;
  const [open, setOpen] = useState<boolean>(false);
  const [title, setTitle] = useState<string>("");
  const formComRef: any = useRef(null);
  useEffect(() => {
    setOpen(openModalFlag);
    setTitle(modalTitle);
  }, [modalTitle, openModalFlag, props.openModalFlag]);
  useEffect(() => {
    if (modalTitle === "新增") {
      formComRef.current?.restForm();
    }
  }, [props.modalTitle, formComRef.current]);
  const handleOk = async () => {
    const res = await formComRef.current.validateForm();
    if (res) {
      const formValue = formComRef.current.getFormValue();
      onOk && onOk(formValue);
      handleCloseModal();
    }
  };
  //  close modal
  const handleCloseModal = () => {
    close && close();
  };
  return (
    <div>
      <Modal
        title={title}
        open={open}
        onOk={handleOk}
        onCancel={handleCloseModal}
      >
        <FormComponent
          FormFiledList={FormFiledList}
          formId={"add"}
          ref={formComRef}
          hasModal={false}
          editData={editData}
          detailid={detailid}
        ></FormComponent>
      </Modal>
    </div>
  );
};
export default memo(Index);
